package com.terabits.smartriver.job;

import com.terabits.smartriver.constants.ModelEnum;
import com.terabits.smartriver.mapper.BoxMapper;
import com.terabits.smartriver.mapper.DeviceMapper;
import com.terabits.smartriver.meta.po.Box;
import com.terabits.smartriver.meta.po.Device;
import com.terabits.smartriver.service.impl.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.terabits.smartriver.util.DateUtils.getDateOnlyYMD;


@Component
public class CheckBox extends BaseService {
    @Autowired
    private BoxMapper boxMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    //    @Scheduled(cron = "0 30 10 ? * *")
    @Scheduled(cron = "0 */1 * * * ?")
    public void CheckDeviceByDate() {

        //获取所有盒子
        List<Box> boxes = boxMapper.selectAll();
        for (Box box : boxes) {
            String boxNum = box.getBoxNum();
            Device device = new Device();
            device.setBoxNum(boxNum);
            List<Device> devices = deviceMapper.select(device);
            List<Device> offLineDeviceList = devices.stream().filter(device1 -> device1.getState() == 3).collect(Collectors.toList());
            List<Device> abnormalDeviceList = devices.stream().filter(device1 -> device1.getState() == 2).collect(Collectors.toList());
            if (offLineDeviceList.size() > 0) {
                //离线
                box.setStatus(ModelEnum.level_offline.getCode());
                boxMapper.updateByPrimaryKey(box);
            } else if (abnormalDeviceList.size() > 0) {
                //异常
                box.setStatus(ModelEnum.level_abnormal.getCode());
                boxMapper.updateByPrimaryKey(box);
            } else {
                //正常
                box.setStatus(ModelEnum.level_normal.getCode());
                boxMapper.updateByPrimaryKey(box);
            }
        }
        System.out.println("检查盒子在线离线结束");
    }
}
